module test_glfw;

import derelict.glfw.glfw;
import derelict.opengl.gl;
import derelict.opengl.glu;

static this()
{
	DerelictGL.load();
	DerelictGLU.load();
	DerelictGLFW.load();

	glfwInit();
}

static ~this()
{
	glfwTerminate();
}

void main()
{
	// Open window
	int ok = glfwOpenWindow(640, 480, // Width and height of window
		8, 8, 8, // Number of red, green, and blue bits for color buffer
		8, // Number of bits for alpha buffer
		24, // Number of bits for depth buffer (Z-buffer)
		0, // Number of bits for stencil buffer
		GLFW_WINDOW // We want a desktop window (could be GLFW_FULLSCREEN)
		);

	// If we could not open a window, exit now
	if(!ok)
	{
		return;
	}

	// Set window title
	glfwSetWindowTitle("My OpenGL program");

	// Enable sticky keys
	glfwEnable(GLFW_STICKY_KEYS);

	bool running = true;
	// Main rendering loop
	do
	{
		// Call our rendering function
		draw();

		// Swap front and back buffers (we use a double buffered display)
		glfwSwapBuffers();

		// Check if the escape key was pressed, or if the window was closed
		running = !glfwGetKey(GLFW_KEY_ESC) && glfwGetWindowParam(GLFW_OPENED);
	}
	while(running);
}

//----------------------------------------------------------------------
//Draw() - Main OpenGL drawing function that is called each frame
//----------------------------------------------------------------------

void draw()
{
	// Get current time
	double t = glfwGetTime();

	int width, height; // Window dimensions
	// Get window size
	glfwGetWindowSize(&width, &height);

	// Make sure that height is non-zero to avoid division by zero
	height = height < 1 ? 1 : height;

	// Set viewport
	glViewport(0, 0, width, height);

	// Clear color and depht buffers
	glClearColor(0.0f, 0.0f, 0.0f, 0.0f);
	glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);

	// Set up projection matrix
	glMatrixMode(GL_PROJECTION); // Select projection matrix
	glLoadIdentity(); // Start with an identity matrix
	gluPerspective( // Set perspective view
		65.0, // Field of view = 65 degrees
		cast(double) width / cast(double) height, // Window aspect (assumes square pixels)
		1.0, // Near Z clipping plane
		100.0 // Far Z clippling plane
	);

	// Set up modelview matrix
	glMatrixMode(GL_MODELVIEW); // Select modelview matrix
	glLoadIdentity(); // Start with an identity matrix
	gluLookAt( // Set camera position and orientation
		0.0, 0.0, 10.0, // Camera position (x,y,z)
		0.0, 0.0, 0.0, // View point (x,y,z)
		0.0, 1.0, 0.0 // Up-vector (x,y,z)
	);

// Here is where actual OpenGL rendering calls would begin...
}
